package com.wica.adapter;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Vector;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.wica.facetube.FaceTubeService;
import com.wica.facetube.R;
import com.wica.model.MovieClip;
import com.wica.view.EfficientList;

public class EfficientListAdapter extends BaseAdapter {
	// *************** Constants ************** //  
    // Set up a random unique ID for message handler
    protected static final int GUIUPDATEIDENTIFIER = 12345;
	private static final int INTERNET_ERROR = -1;

	// Log constant
	protected static final String LOG_TAG = "PTv.EfficientListAdapter";
	
    // *************** Attributes ************************* //  
	protected FaceTubeService fts;
	protected Vector<String> data = new Vector<String>();
	protected Vector<BitmapDrawable> bmpd = new Vector<BitmapDrawable>();
	protected Vector<MovieClip> listOfMovies = new Vector<MovieClip>();
    // mInflater cache the LayoutInflate to avoid asking for a new one each time.
    protected LayoutInflater mInflater;
    // Set up a progress dialog
    protected ProgressDialog mypd = null;
	protected EfficientList list;
	protected EfficientListAdapter adapter;
	
    static class ViewHolder {
        TextView text;
        ImageView icon;
    }// ViewHolder class
    
	// *************** Methods **************************** //

    public EfficientListAdapter(EfficientList list) {
        // Cache the LayoutInflate to avoid asking for a new one each time.
        mInflater = LayoutInflater.from((Context)list);
        this.list=list;
        // we get facetube connection
        fts = new FaceTubeService();
    }// EfficientListAdapter creator method
           
    /**
     * The number of items in the list is determined by the number of speeches
     * in our array.
     *
     * @see android.widget.ListAdapter#getCount()
     */
    public int getCount() {
    	return data.size();
    }// getCount method

    /**
     * Since the data comes from an array, just returning the index is
     * sufficient to get at the data. If we were using a more complex data
     * structure, we would return whatever object represents one row in the
     * list.
     *
     * @see android.widget.ListAdapter#getItem(int)
     */
    public Object getItem(int position) {
        return listOfMovies.get(position);
    }// getItem method

    /**
     * Use the array index as a unique id.
     *
     * @see android.widget.ListAdapter#getItemId(int)
     */
    public long getItemId(int position) {
        return position;
    }// getItemId method

    /**
     * Make a view to hold each row.
     *
     * @see android.widget.ListAdapter#getView(int, android.view.View,
     *      android.view.ViewGroup)
     */
    public View getView(int position, View convertView, ViewGroup parent) {
        // A ViewHolder keeps references to children views to avoid unneccessary calls
        // to findViewById() on each row.
        ViewHolder holder;

        // When convertView is not null, we can reuse it directly, there is no need
        // to reinflate it. We only inflate a new View when the convertView supplied
        // by ListView is null.
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
            // Creates a ViewHolder and store references to the two children views
            // we want to bind data to.
            holder = new ViewHolder();
            holder.text = (TextView) convertView.findViewById(R.id.text);
            holder.icon = (ImageView) convertView.findViewById(R.id.icon);
            convertView.setTag(holder);
        } else {
            // Get the ViewHolder back to get fast access to the TextView
            // and the ImageView.
            holder = (ViewHolder) convertView.getTag();
        }
        // Bind the data efficiently with the holder.
        if (data.get(position)==null)
            holder.text.setText("");
        else
        	holder.text.setText(data.get(position));
        if (bmpd.get(position)==null)
        	holder.icon.setImageURI(Uri.parse("http://i.ytimg.com/vi/-wIEihDAcpU/1.jpg"));
        else
        	holder.icon.setImageDrawable(bmpd.get(position));
        	//holder.icon.setImageURI(Uri.parse("http://i.ytimg.com/vi/-wIEihDAcpU/1.jpg"));
        return convertView;
    }// getViewed method
    
    protected void checkPreconditions() {
	}

	protected void getListOfVideosMethod() {
	}// getListOfVideosMethod method
	
	protected void getListOfVideosThread(){	
		if (!internetNetworkAvailable()){
			list.showDialog(-1);
		}else{
	    	// Start a progress dialog here       
			if (list!=null)
	        mypd = ProgressDialog.show(	(Context)list, 
	        							"Searching", 
	        							"Please wait...", 
	        							false);        
	        Thread t = new Thread() {
	        	public void run() {
	        		getListOfVideosUnthreaded();    		        		    
	        		// Send a message to the handler                    
	        		Message message = new Message();                  
	        		message.what = ELAMostViewed.GUIUPDATEIDENTIFIER;                    
	        		EfficientListAdapter.this.myGUIUpdateHandler.sendMessage(message);			
	        	}
	        };      	              
	        t.start();		
		}// if 
	}// getVideoThread method
    
	protected void refresh(){
		
	}
	
	protected void getListOfVideosUnthreaded(){
		checkPreconditions();
		// Local Variables
		int i;
		URL url;
		InputStream is;
		// we call the service
		getListOfVideosMethod();
		// we create vectors with both data and thumbnails
		// we do not invoke a virtual method to enhance performance
		if (listOfMovies.size()==0 && !internetNetworkAvailable()){
			list.showDialog(-1);			
		}
		for (i=0;i<listOfMovies.size();i++){
			int minutes = listOfMovies.get(i).getDuration()/60;
			int seconds = listOfMovies.get(i).getDuration()-(60*minutes);
			data.add(listOfMovies.get(i).getTitle()+" ["+minutes+":"+seconds+"]");			
			try {
				url = new URL(listOfMovies.get(i).getURLThumbnail());
				is = (InputStream) url.getContent();
				bmpd.add((BitmapDrawable) BitmapDrawable.createFromStream(is , "youtube"));	            
			} catch (MalformedURLException e) {
				Log.e(LOG_TAG,e.toString());
			} catch (IOException e) {
				Log.e(LOG_TAG,e.toString());
			}
		}//for
    }//getListOfVideosUnthreaded method    
	
    // Set up the message handler
    Handler myGUIUpdateHandler = new Handler() {
    	public void handleMessage(Message msg) {
    		switch (msg.what) {                   
	    		case ELAMostViewed.GUIUPDATEIDENTIFIER: 	
	    			Log.v(LOG_TAG, LOG_TAG);
	    			if (list!=null)
	    				list.setListAdapter(adapter);
	    			if (mypd!=null)
	    				mypd.dismiss();
//	    			if (firstTimeHere){
//	    				firstTimeHere=false;
////	    				call(list);
//	    			}	    				
	    			break;
	    		case EfficientListAdapter.INTERNET_ERROR: 	    
	    			mypd.dismiss();
	    			break;
	    		default:
	    			break;	    		
    		}//switch
    		super.handleMessage(msg);       
    	}//handleMessage method
    };// myGUIUpdateHandler

    protected boolean internetNetworkAvailable() {
        // Local Variables
    	ConnectivityManager connectivityManager = (ConnectivityManager)(((Context)list).getSystemService(Context.CONNECTIVITY_SERVICE));
        NetworkInfo[] allNetworkInfo = connectivityManager.getAllNetworkInfo();
        int i;
        
        for (i=0;i<allNetworkInfo.length;i++){
        	NetworkInfo networkInfoItem = allNetworkInfo[i];        	
            if (networkInfoItem.isAvailable()){
            	return true;
            }// if
        }// for
		return false;
	}// internetNetworkAvailable method

}// EfficientListAdapter class